﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using OrmAuto;
using AjaxControlToolkit;
using System.Data;
using System.Data.SqlClient;

public partial class Contents_GestioneAgentiVendita : BaseClassPagine
{
    //QueryUtenti mqUtenti = null;
    //Querier mQuery= null ;

    protected readonly string mVista = "vANNVendita";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.Page.User.Identity.IsAuthenticated)
            Response.Redirect(FormsAuthentication.LoginUrl); //	

        if (!IsPostBack)
            inizializza();

    }

    private void inizializza()
    {
        QuerierLight qL = new QuerierLight();

        var idU = qL.getUtenteID(this.Page.User.Identity.Name);
        myIdU.Value = idU.ToString();

    }//fM


    [System.Web.Services.WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    public static CascadingDropDownNameValue[] GetDropDownContents(
                                string knownCategoryValues, string category)
    {
        QueryLuoghi mQuery = new QueryLuoghi();
        var arrCatena = knownCategoryValues.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);

        if (category.Equals("StatoLuogoMerce"))
        {
            if (arrCatena == null) return new CascadingDropDownNameValue[0];

            var arr = arrCatena[0].Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
            var idStato = int.Parse(arr[1]);
            var regioni = mQuery.getRegioni(idStato).Select(
                    r => new CascadingDropDownNameValue() { name = r.REG_REGIONE, value = r.REG_ID.ToString() }).ToArray();
            return regioni;
        }

        if (category.Equals("RegioneLuogoMerce"))
        {
            if (arrCatena == null) return new CascadingDropDownNameValue[0];

            var arr1 = arrCatena[0].Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
            var arr2 = arrCatena[1].Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries);

            var idStato = int.Parse(arr1[1]);
            var idRegioni = -1;
            if (!int.TryParse(arr2[1], out idRegioni)) return new CascadingDropDownNameValue[0];

            var provincie = mQuery.getProvince(idRegioni).Select(
                    p => new CascadingDropDownNameValue() { name = p.PROV_PROVINCIA, value = p.PROV_ID.ToString() }).ToArray();
            return provincie;
        }

        return new CascadingDropDownNameValue[0];
    }


    [System.Web.Services.WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    public static CascadingDropDownNameValue[] GetDropDownModelli(
                                string knownCategoryValues, string category)
    {
        var arrCatena = knownCategoryValues.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);

        if (category.Equals("Modelli"))
        {
            if (arrCatena == null) return new CascadingDropDownNameValue[0];
            QuerierMarcheModelli mQuery = new QuerierMarcheModelli();

            var arr = arrCatena[0].Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
            //var idmarca = int.Parse(arr[1]);
            var marca = arr[1];
            int idMarca = 0;
            int.TryParse(marca, out idMarca);
            var modelli = mQuery.getModelli(idMarca).Select(
                    m => new CascadingDropDownNameValue() { name = m.Modello, value = m.ID.ToString() }).ToList();
            modelli.Insert(0, new CascadingDropDownNameValue { isDefaultValue = false, name = "Tutti / All", value = "0" });
            return modelli.ToArray();
        }

        return new CascadingDropDownNameValue[0];
    }//fM


    protected void SqlDataSource_AnnVendita_Inserting(object sender, SqlDataSourceCommandEventArgs e)
    {
        var c = e.Command;
    }
    protected void SqlDataSource_AnnVendita_Inserted(object sender, SqlDataSourceStatusEventArgs e)
    {
        var ex = e.Exception;
    }//fM


    //annunci di vendita
    protected void ShowButton_Click(object sender, ImageClickEventArgs e)
    {
        startRicerca();
    }

    private void startRicerca()
    {
        QuerierLight qL = new QuerierLight();
        var idUtente = qL.getUtenteID(Page.User.Identity.Name);

        if (!(myIdU.Value == idUtente.ToString()))
            Response.Redirect("~/Genericerror.aspx?error=" + Server.UrlEncode("Utente non identificato."));

        // showVistaAnnunci(true, idUtente, idMarca, idModello, idPossesso, abilitato);

        try
        {
            showRicerca();
        }
        catch (Exception ex)
        {
            myLiteralMsg.Text = "Errore : " + ex.Message;
        }
    }//fM

    public void showRicerca()
    {
        if (Request.Form == null) return;
        if (!Request.Form.HasKeys()) return;

        var f = Request.Form;
        var all = f.AllKeys;

        var marca = f[all.Where(k => k.IndexOf("myDropMarche") > 0).FirstOrDefault()];
        var modello = f[all.Where(k => k.IndexOf("myDropModelli") > 0).FirstOrDefault()];
        var possesso = f[all.Where(k => k.IndexOf("myDropPossessi") > 0).FirstOrDefault()];
        var colore = f[all.Where(k => k.IndexOf("myDropColori") > 0).FirstOrDefault()];
        var stati = f[all.Where(k => k.IndexOf("myStatiDrop") > 0).FirstOrDefault()];
        var tipologia = f[all.Where(k => k.IndexOf("myTipiDrop") > 0).FirstOrDefault()];


        var priceStart = f[all.Where(k => k.IndexOf("myPrezzoStartDrop") > 0).FirstOrDefault()];
        var priceFinal = f[all.Where(k => k.IndexOf("myPrezzoFinaleDrop") > 0).FirstOrDefault()];

        var km_Start = f[all.Where(k => k.IndexOf("myKmStartDrop") > 0).FirstOrDefault()];
        var km_Fine = f[all.Where(k => k.IndexOf("myKmFineDrop") > 0).FirstOrDefault()];

        bool ivaDeducibile = false;
        var ivaDed = f[all.Where(k => k.IndexOf("myIvaDedCheck") > 0).FirstOrDefault()];
        if (!string.IsNullOrEmpty(ivaDed))
        {
            if (ivaDed.Equals("on", StringComparison.InvariantCultureIgnoreCase))
                ivaDeducibile = true;
        }

        if (!string.IsNullOrEmpty(priceStart))
            priceStart = priceStart.Replace(".", "");
        if (!string.IsNullOrEmpty(priceFinal))
            priceFinal = priceFinal.Replace(".", "");

        if (!string.IsNullOrEmpty(km_Start))
            km_Start = km_Start.Replace(".", "");
        if (!string.IsNullOrEmpty(km_Fine))
            km_Fine = km_Fine.Replace(".", "");


        int idMarca = 0, idModello = 0, idPossesso = 0, idColore = 0, idTipologia = 0, idStato = 0;
        int prezzoStart = 0, prezzoFinal = 0, kmStart = 0, kmFine = 0;

        int.TryParse(marca, out idMarca);
        int.TryParse(modello, out idModello);
        int.TryParse(possesso, out idPossesso);
        int.TryParse(colore, out idColore);
        int.TryParse(tipologia, out idTipologia);
        int.TryParse(stati, out idStato);
        int.TryParse(priceStart, out prezzoStart);
        int.TryParse(priceFinal, out prezzoFinal);
        int.TryParse(km_Start, out kmStart);
        int.TryParse(km_Fine, out kmFine);

        if (possesso.Equals("1"))//1 = nuova
        { kmStart = 0; kmFine = 0; }

        DataTable dati = null;

        try
        {
            dati = new OrmAuto.RicercheSql().sp_vAnnVenditaGetBy(
                    idMarca, idModello, idPossesso, idColore, idTipologia, idStato, prezzoStart, prezzoFinal,
                    kmStart, kmFine, ivaDeducibile, true);
        }
        catch (Exception ex)
        {
            ;
        }

        this.GridViewAnnunci .DataSource = dati;
        this.GridViewAnnunci.DataBind();
    }//fM


    protected void GridViewAnnunci_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {

    }//fM

    protected void GridViewAnnunci_SelectedIndexChanged(object sender, EventArgs e)
    {
        var grid = ((GridView)sender);
        if (grid.SelectedDataKey == null) return;
        var ID = grid.SelectedDataKey.Value;
        if (ID == null) return;
        var id = (int)ID;
        myAnnuncioSql1.AggiornaAnnuncio(id);

        tabContainer1.ActiveTabIndex = 1;

    }//fM


    protected void NewButton_Click(object sender, ImageClickEventArgs e)
    {
        myAnnuncioSql1.NuovoAnnuncio();
        tabContainer1.ActiveTabIndex = 1;
    }//fM

    ////////
    protected void GridViewAnnunci_Sorting(object sender, GridViewSortEventArgs e)
    {
        var sort =
                e.SortDirection == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending;

        GridViewAnnunci.DataBind();
        //((GridView)sender).Sort(e.SortExpression , sort); 

    }

    protected void GridViewAnnunci_Sorted(object sender, EventArgs e)
    {

    }



}//fM
